package com.sys.app.web.base;


import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import com.sys.app.entity.sys.SysAccount;
import com.sys.app.entity.sys.myConstants;
import com.sys.app.entity.token.BaseUserInfo;
import com.sys.app.entity.token.TokenUtil;
import com.sys.app.entity.util.StringUtil;

import org.apache.logging.log4j.util.Strings;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class TokenInterceptor implements HandlerInterceptor {
    Logger logger = LoggerFactory.getLogger(TokenInterceptor.class);
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        response.setCharacterEncoding("utf-8");//防止前端乱码
        request.setCharacterEncoding("utf-8");//防止前端乱码
        response.setContentType("text/html;charset=utf-8");
        //跨域请求会首先发一个option请求，直接返回正常状态并通过拦截器
        if(request.getMethod().equals("OPTIONS")){
            response.setStatus(HttpServletResponse.SC_OK);
            return true;
        }

        //获取到token：正确格式 header参数 Authorization  Bearer+空格+token
        String token = request.getHeader(myConstants.AUTHORIZATION_KEY);
        if (StringUtil.isNotBlank(token)){
            if (!StrUtil.startWithIgnoreCase(token, myConstants.JWT_PREFIX)) {
                try {
                    JSONObject json=new JSONObject();
                    json.set("code","1");
                    json.set("message","失败");
                    json.set("result","授权缺失：Bearer");
                    response.getWriter().append(json.toString());
                    logger.info("授权缺失：Bearer");
                } catch (Exception e) {
                    logger.error(e.toString());
                    return false;
                }
            }
            //token验证jwt，此项为空，就是一般sesion验证
            token = StrUtil.replaceIgnoreCase(token, myConstants.JWT_PREFIX, Strings.EMPTY);
            boolean result= TokenUtil.verify(token);
            if (result){
                //存储用户信息
                SysAccount user=TokenUtil.getUserInfo(token);
                BaseUserInfo.setUser(user);
                return true;
            }else{
                try {
                    JSONObject json=new JSONObject();
                    json.set("code","1");
                    json.set("message","失败");
                    json.set("result","token 授权失败");
                    response.getWriter().append(json.toString());
                    logger.info("token 授权失败:"+token);
                } catch (Exception e) {
                    logger.error(e.toString());
                    return false;
                }
            }
        }else{
            //sesion验证
            //判断用户是否登录
            if (request.getSession().getAttribute(myConstants.SYS_ACCOUNT_SESSION_KEY)==null) {
                logger.info(String.format("获取Session失败,请求地址：%s",request.getRequestURI()));
                response.sendRedirect(request.getContextPath() + "/login/index.do");
            } else {
                logger.info(String.format("请求地址：%s",request.getRequestURI()));
                String sys_account_session=request.getSession().getAttribute(myConstants.SYS_ACCOUNT_SESSION_KEY).toString();
                if (!StrUtil.startWithIgnoreCase(sys_account_session, myConstants.JWT_PREFIX)) {
                    try {
                        JSONObject json=new JSONObject();
                        json.set("code","1");
                        json.set("message","失败");
                        json.set("result","授权缺失：Bearer");
                        response.getWriter().append(json.toString());
                        logger.info("授权缺失：Bearer");
                    } catch (Exception e) {
                        logger.error(e.toString());
                        return false;
                    }
                }
                sys_account_session = StrUtil.replaceIgnoreCase(sys_account_session, myConstants.JWT_PREFIX, Strings.EMPTY);
                boolean result= TokenUtil.verify(sys_account_session);
                if(result) {
                    SysAccount user = TokenUtil.getUserInfo(sys_account_session);
                    BaseUserInfo.setUser(user);
                    logger.info(String.format("获取Session成功-[%s],请求地址：%s", user.getCode(), request.getRequestURI()));
                    return true;
                }else{
                    try {
                        JSONObject json=new JSONObject();
                        json.set("code","1");
                        json.set("message","失败");
                        json.set("result","session 授权失败");
                        response.getWriter().append(json.toString());
                        logger.info("session 授权失败:"+sys_account_session);
                    } catch (Exception e) {
                        logger.error(e.toString());
                        return false;
                    }
                }
            }
        }
        return false;
    }

    /**
     * 避免内存泄露
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        BaseUserInfo.removeUser();
    }
}
